#coding=utf-8
'''
Created on 2017-04-20

@author: sandy
'''
import os
from twisted.python import log
from logging.handlers import TimedRotatingFileHandler
import logging
import time
import RemoteManager


class LogHandler(logging.Handler):
    def emit(self, record):
        try:
            msg = self.format(record)
            #manager.instance.sendPacket(managerbuild.exceptionLog(msg))
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

class LogManager(object):
    def __init__(self):
        self.logformat = u'%(asctime)s %(levelname)s %(message)s'
        logDir = u"log"
        self.logPath = os.path.dirname(__file__) + "/../" + logDir + "/"
        isExit = os.path.exists(self.logPath)
        if isExit == False:
            os.makedirs(self.logPath)

    
    def setupLog(self,loglevel,logfile, isdaemon):
        logging.getLogger().setLevel(loglevel)
        logfile = logfile.replace('.','-%d.' % RemoteManager.instance.sid)
        self.fileloghandler = TimedRotatingFileHandler(filename= self.logPath + logfile,when='D',interval=1)
        self.fileloghandler.setLevel(loglevel)
        formatter = logging.Formatter(self.logformat)
        self.fileloghandler.setFormatter(formatter)
        logging.getLogger().addHandler(self.fileloghandler)

        logging.captureWarnings(True)
        log.PythonLoggingObserver().start()
        if isdaemon:
            handler = LogHandler()
            handler.setLevel(logging.ERROR)
            logging.getLogger().addHandler(handler)
        else:
            handler = logging.StreamHandler()
            handler.setLevel(loglevel)
            formatter = logging.Formatter(self.logformat)
            handler.setFormatter(formatter)
            logging.getLogger().addHandler(handler)

    def setLogLevel(self, level):
        logging.getLogger().setLevel(level)
        self.fileloghandler.setLevel(level)
            

instance = LogManager();

if __name__ == "__main__":
    pass
